﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using IEx.Common;
using IEx.Utilities;

namespace IEx.ParserBuilder.RestaurantFoody
{
    public class FoodyRequestBuilder : DefaultRequestBuilder
    {
        public override void BeginBuildRequest(SourceItem item)
        {
            // Daily Url doesn't need to buid request
            if (!string.IsNullOrEmpty(item.DailyUrl) && item.DailyUrl.Equals(item.Url, StringComparison.OrdinalIgnoreCase))
                return;

            DateTime latestDate = DateTime.Now;
            this.InternalBuildRequest(item, latestDate, DateTime.Now);
        }

        protected void InternalBuildRequest(SourceItem item, DateTime from, DateTime to)
        {
            //STEP 1: assign values for search form
            this.Method = "POST";
            this.ContentType = "application/x-www-form-urlencoded";
            if (!string.IsNullOrEmpty(item.PrevResponseHtml))
            {
                string html = item.PrevResponseHtml;
                string startHtml = "class=\"filter-results\"";
                string endHtml = "id=\"addWishListPopup\"";
                string remainHtml = Utility.GetHtmlBody(html, startHtml, endHtml);
                int page = 1;

                Regex regNextPage = new Regex("<span\\s*data-bind=\"text: currentPage.*?</span>");
                Match mNextPage = regNextPage.Match(remainHtml);
                if (mNextPage.Success)
                {
                    string pageHtml = mNextPage.Value.Trim();
                    bool isNextPage = int.TryParse(RegexUtility.ExtractTextFromHtmlTag(pageHtml), out page);
                    if (isNextPage)
                    {
                        page = page + 1;
                    }
                }

                this.AttachRequestParam("vt", "row");
                this.AttachRequestParam("st", "1");
                this.AttachRequestParam("dt", "undefined");
                this.AttachRequestParam("c", "3");
                this.AttachRequestParam("page", page.ToString());
                this.AttachRequestParam("provinceId", "218");
                this.AttachRequestParam("categoryId", "3");
                this.AttachRequestParam("append", "true");
            }
        }
    }
}
